<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加订单</el-button>

    <el-table :data="paginatedOrders" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="status" label="状态" width="100"></el-table-column>
      <el-table-column prop="price" label="价格" width="100"></el-table-column>
      <el-table-column prop="userID" label="用户ID" width="100"></el-table-column>
      <el-table-column prop="tprice" label="总价格" width="100"></el-table-column>
      <el-table-column prop="buyNum" label="购买数量" width="100"></el-table-column>
      <el-table-column prop="spaceType" label="空间类型" width="150"></el-table-column>
      <el-table-column prop="flightID" label="航班ID" width="100"></el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="150"></el-table-column>
      <el-table-column prop="orderNo" label="订单编号" width="150"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteOrder(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        style="margin-top: 20px;"
        background
        layout="prev, pager, next"
        :total="totalOrders"
        :page-size="pageSize"
        @current-change="handlePageChange"
    ></el-pagination>

    <!-- 编辑订单对话框 -->
    <el-dialog title="编辑订单" v-model="isEditDialogVisible">
      <el-form :model="editForm">
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="已支付" value="payed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="editForm.userID"></el-input>
        </el-form-item>
        <el-form-item label="总价格">
          <el-input v-model="editForm.tprice"></el-input>
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input v-model="editForm.buyNum"></el-input>
        </el-form-item>
        <el-form-item label="空间类型">
          <el-input v-model="editForm.spaceType"></el-input>
        </el-form-item>
        <el-form-item label="航班ID">
          <el-input v-model="editForm.flightID"></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="editForm.orderTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="editForm.orderNo"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrder">确认</el-button>
      </div>
    </el-dialog>

    <!-- 添加订单对话框 -->
    <el-dialog title="添加订单" v-model="isAddDialogVisible">
      <el-form :model="addForm">
        <el-form-item label="状态">
          <el-select v-model="addForm.status">
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="已支付" value="payed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="addForm.userID"></el-input>
        </el-form-item>
        <el-form-item label="总价格">
          <el-input v-model="addForm.tprice"></el-input>
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input v-model="addForm.buyNum"></el-input>
        </el-form-item>
        <el-form-item label="空间类型">
          <el-input v-model="addForm.spaceType"></el-input>
        </el-form-item>
        <el-form-item label="航班ID">
          <el-input v-model="addForm.flightID"></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="addForm.orderTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="addForm.orderNo"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrder">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import moment from 'moment'
import { getOrderList, deleteOrder as deleteOrderAPI, updateOrder as updateOrderAPI, addOrder as addOrderAPI } from '@/api/order.js'
import { ElMessageBox, ElMessage } from 'element-plus'

const orders = ref([])
const currentPage = ref(1)
const pageSize = 10
const totalOrders = ref(0)
const paginatedOrders = ref([])

const fetchOrders = async () => {
  try {
    const response = await getOrderList()
    if (response.code === 1) {
      orders.value = response.data.map(order => ({
        ...order,
        orderTime: moment(order.orderTime).format('YYYY-MM-DD HH:mm:ss')
      }))
      totalOrders.value = orders.value.length
      paginateOrders()
    } else {
      throw new Error(response.msg)
    }
  } catch (error) {
    console.error('Error fetching orders:', error)
  }
}

const paginateOrders = () => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  paginatedOrders.value = orders.value.slice(start, end)
}

const handlePageChange = (page) => {
  currentPage.value = page
  paginateOrders()
}

const isEditDialogVisible = ref(false)
const editForm = ref({
  id: '',
  status: '',
  price: '',
  userID: '',
  tprice: '',
  buyNum: '',
  spaceType: '',
  flightID: '',
  orderTime: '',
  orderNo: ''
})

const isAddDialogVisible = ref(false)
const addForm = ref({
  status: 'pending',
  price: '',
  userID: '',
  tprice: '',
  buyNum: '',
  spaceType: '',
  flightID: '',
  orderTime: '',
  orderNo: ''
})

const openEditDialog = (order) => {
  editForm.value = {
    ...order,
    orderTime: moment(order.orderTime, 'YYYY-MM-DD HH:mm:ss').toDate()
  }
  isEditDialogVisible.value = true
}

const openAddDialog = () => {
  addForm.value = {
    status: 'pending',
    price: '',
    userID: '',
    tprice: '',
    buyNum: '',
    spaceType: '',
    flightID: '',
    orderTime: '',
    orderNo: ''
  }
  isAddDialogVisible.value = true
}

const updateOrder = async () => {
  try {
    const updatedOrder = {
      ...editForm.value,
      orderTime: moment(editForm.value.orderTime).format('YYYY-MM-DD HH:mm:ss')
    }
    await updateOrderAPI(updatedOrder)
    ElMessage({
      type: 'success',
      message: '更新成功!',
    })
    isEditDialogVisible.value = false
    fetchOrders()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '更新失败',
    })
    console.error('Error updating order:', error)
  }
}

const addOrder = async () => {
  try {
    const newOrder = {
      ...addForm.value,
      orderTime: moment(addForm.value.orderTime).format('YYYY-MM-DD HH:mm:ss')
    }
    await addOrderAPI(newOrder)
    ElMessage({
      type: 'success',
      message: '添加成功!',
    })
    isAddDialogVisible.value = false
    fetchOrders()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '添加失败',
    })
    console.error('Error adding order:', error)
  }
}

const deleteOrder = async (id) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该订单, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteOrderAPI(id)
    ElMessage({
      type: 'success',
      message: '删除成功!',
    })
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: '删除失败',
      })
    }
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
/* 可以添加你的样式 */
</style>
